package cn.wolfcode.cms.service.impl;

import cn.wolfcode.cms.domain.Permission;
import cn.wolfcode.cms.domain.Role;
import cn.wolfcode.cms.mapper.RoleMapper;
import cn.wolfcode.cms.query.QueryObject;
import cn.wolfcode.cms.service.IRoleService;
import cn.wolfcode.cms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    public void delete(Long id) {
        if(id != null){
            //打破关系
            roleMapper.deleteRelation(id);

            roleMapper.deleteByPrimaryKey(id);
        }
    }

    public void save(Role role) {
        //添加角色
        roleMapper.insert(role);

        //维护与权限关系
        List<Permission> ps = role.getPermissions();
        if(ps != null && ps.size() > 0){
            for (Permission p : ps) {
                roleMapper.insertRelation(role.getId(), p.getId());
            }
        }

    }


    public void update(Role role) {
        //打破关系
        roleMapper.deleteRelation(role.getId());
        roleMapper.updateByPrimaryKey(role);

        //维护与权限关系
        List<Permission> ps = role.getPermissions();
        if(ps != null && ps.size() > 0){
            for (Permission p : ps) {
                roleMapper.insertRelation(role.getId(), p.getId());
            }
        }

    }

    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = roleMapper.queryForCount(qo);
        if(total == 0){
           return new PageResult();
        }
        List<Role> rows = roleMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    public List<Long> getRoleIdsByEmployeeId(Long id) {
        return roleMapper.getRoleIdsByEmployeeId(id);
    }

    public List<String> getRoleSnByEmpId(Long id) {
        return roleMapper.getRoleSnByEmpId(id);
    }


}
